package com.kxn.multi.module.security.handler;

import com.alibaba.fastjson.JSON;
import com.kxn.multi.module.common.pojo.ApiResult;
import com.kxn.multi.module.common.pojo.ResultCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 未登录或者认证失败处理
 *
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
//        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException == null ?" Unauthorized" : authException.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ApiResult apiResult = ApiResult.error(ResultCode.UNAUTHORIZED);
        out.write(JSON.toJSONString(apiResult));
        out.flush();
        out.close();
    }
}
